package org.zttc.itat.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.zttc.itat.dao.ISortDao;
import org.zttc.itat.model.Sort;
import org.zttc.itat.model.SortScope;
import org.zttc.itat.model.SortType;

@Service("sortService")
public class SortService implements ISortService {
	
	@Resource(name="sortDao")
	private ISortDao sortDao;

	@Override
	public void add(Sort sort) {
        sortDao.add(sort);
	}
	
	@Override
	public void update(Sort sort) {
        sortDao.update(sort);
	}

	@Override
	public void delete(int id) {
		//1、判断是否有子栏目，如果有抛出异常
		//2、判断是否有新闻，如果有抛出异常
        sortDao.delete(id);
	}

	@Override
	public Sort load(int id) {
		
		return sortDao.load(id);
	}

	@Override
	public List<Sort> listAllSort() {
		String hql ="from Sort";
		return sortDao.list(hql);
	}

	@Override
	public void addTypeSort(int sortId, int tSortId) {
		  String hql = "select st from SortType st where id=?";
	      SortType st =(SortType)sortDao.queryByHql(hql, tSortId);
	      SortScope ss = new SortScope();
	      ss.setSortId(sortId);
	      ss.setSortType(st);
	      sortDao.addObj(ss);
	}

	@Override
	public void addTypeSort(int sortId, int[] tSortIds) {
           for(int i=0;i<tSortIds.length;i++){
        	   this.addTypeSort(sortId, tSortIds[i]);
           } 	
	}

	@Override
	public void deleteTypeSort(int sortId, int tSortId) {
		String hql = "delete SortScope ss where ss.sortId=? and ss.sortType.id=?";
		sortDao.executeByHql(hql,new Object[]{sortId,tSortId});
	}

	@Override
	public void deleteScopeDep(int sortId) {
		String hql = "delete SortScope ss where ss.sortId=?";
		sortDao.executeByHql(hql,new Object[]{sortId});
	}

	@Override
	public List<SortType> listScopeSort(int sortId) {
		List<SortType> listSt= new ArrayList<SortType>();
		String hql = "select st from SortScope ss left join ss.sortType st where ss.sortId=?";
		List<Object> listObj = sortDao.listByObj(hql, sortId);
		for(Object obj:listObj){
			SortType sort =(SortType)obj;
			listSt.add(sort);
		}
		return listSt;
	}
}
